//app.js
const QQMapWX = require('dist/js/qqmap-wx-jssdk.min.js');
const qqmapsdk = new QQMapWX({
  key: 'HLFBZ-EGZK6-MVQS6-ESMKT-T2G37-GIB2U'
});
let util = require('utils/util.js');
let _this, userInfoReady = true;
let G = {}
// G.APP_LINK = 'http://192.168.1.253:8080/goldkey';
// G.APP_LINK = 'http://192.168.1.107:8080/goldkey';
// G.APP_LINK = 'https://www.ulpey.com/goldkey';
G.APP_LINK = 'https://www.taiyanglun.vip/goldkey';
let list = {}, link = {};
list.salonObject = '/salonObject/list';
list.salonType = '/salonType/list';
list.banner = '/banner/list';
list.signUpList = '/salonObject/signUpList';
list.userSign = '/userSign/product/list';
// 
link.listDetails = '/salonObject/get';
link.oderVip = '/vip/orderVip';
link.config = '/config';
link.userSign = '/userSign/getRecords';
link.sign = '/userSign/sign';
link.signPoints = '/userSign/points';
link.signUp = '/salonObject/signUp';
link.getLpInfo = '/user/lpinfo/get';
link.saveLpInfo = '/user/lpinfo/save';
link.exchange = '/userSign/product/exchange';
link.like = '/salon/praise/save';
link.joinUser = '/salonObject/get/joinUser';

App({
  onLaunch: function () {
    _this = this;
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs);
    _this.getCityList();
  },
  onShow: function () {
    console.log("app.onShow");
    wx.redirectTo({
      url: '/pages/index/index',
    })
  },
  onHide: function () {
    console.log("app.onHide");
  },
  globalData: {
    // 地址
    appLink: G.APP_LINK,
    // 未授权获取信息按钮
    unauthorizedUserInfo: true,
    userInfo: null,         // 微信user信息
    programUserInfo: null,  // 后台user信息
    telPhone: '400-8035813',
    address: {}
  },
  /**
   * 地址
   */
  getCityList: function () {
    // 获取全部省市
    qqmapsdk.getCityList({
      success: function (res) {
        let provinceAll = res.result[0];
        let province = [];
        for (var i = 0; i < provinceAll.length; i++) {
          province.push(provinceAll[i].fullname);
        }
        _this.globalData.address.allArea = res.result;
        _this.globalData.address.provinceAll = res.result[0];
        _this.globalData.address.multiArray = [province, []];
        _this.globalData.address.multiIndex = [0, 0];
        _this.getAddress();
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        console.log(res);
      }
    });
  },
  //获取当前地址
  getAddress: function () {
    // 获取当前地址
    wx.getLocation({
      success: function (res) {
        console.log(res);
        //2、根据坐标获取当前位置名称，显示在顶部:腾讯地图逆地址解析
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function (rs) {
            let multiArray = _this.globalData.address.multiArray;
            let address = rs.result.address_component;
            for (var i = 0; i < multiArray[0].length; i++) {
              if (address.province == multiArray[0][i]) {
                _this.globalData.address.multiIndex = [i, 0];
                _this.globalData.address.provinceName = multiArray[0][i];
                _this.globalData.address.cityName = address.city;
                _this.globalData.address.i = i;
              }
            }
          }
        })
      },
    })
  },
  /**
     * 登陆
     */
  // 获取用户信息
  getUserInfo: function (callback) {
    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              _this.globalData.userInfo = res.userInfo;
              _this.globalData.userInfoAll = res;
              _this.globalData.unauthorizedUserInfo = false;
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (userInfoReady) {
                _this.userInfoReadyCallback(res, function (rs) {
                  callback ? callback(rs) : '';
                })
              } else {
                userInfoReady = true;
                callback ? callback(res) : '';
              }
            }
          })
        } else if (!!res.authSetting) {
          _this.globalData.unauthorizedUserInfo = true;
          callback ? callback(false) : '';
        }
      },
      fail: res => {
        console.log(res);
      }
    })
  },
  // 获取微信code
  judgeGetUserInfo(callback) {
    //登录获取code
    wx.login({
      success: function (res) {
        if (res.code) {
          console.log('获取微信code', res.code);
          _this.getUserInfoProgram(res.code, function (res) {
            callback ? callback(res) : '';
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      }
    });
  },
  // 获取用户信息
  getUserInfoProgram(a, callback) {
    console.log('获取用户信息0=');
    // 微信登录械友 通过code获取械友userCode
    wx.request({
      url: G.APP_LINK + '/user/login/verify',
      method: 'GET',
      data: {
        code: a
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log('获取用户信息1=', res);
        if (res.data.data.id && res.data.data.name) {
          console.log('获取用户信息2=', res.data.data);
          _this.globalData.programUserInfo = res.data.data;
          callback(res.data.data);
        } else {
          // // 获取用户信息
          console.log('获取用户信息3=', res);
          var userInfo,
            openid = res.data.data.openid;
          /*
          * 解码用户信息
          */
          userInfoReady = false;
          // 获取用户信息
          _this.getUserInfo(function (res) {
            var userInfoData = _this.globalData.userInfoAll;
            wx.request({
              url: G.APP_LINK + '/user/userinfo/decode', //仅为示例，并非真实的接口地址
              method: 'GET',
              data: {
                encryptedData: userInfoData.encryptedData,
                openId: openid,
                iv: userInfoData.iv
              },
              header: {
                'content-type': 'application/json' // 默认值
              },
              success: function (res) {
                console.log('获取用户信息4=', res);
                _this.globalData.programUserInfo = res.data.data;
                wx.setStorage({
                  key: 'programUserInfo',
                  data: res.data.data,
                })
                callback(res.data.data);
              },
              fail: function (res) {
                console.log(res);
              }
            })
          })

        }
      },
      fail: function (res) {
        console.log('获取用户信息5=', res);
        console.log(res);
      }
    })
  },
  // 根据用户信息获取电话
  getUserPhone(encryptedData, openid, iv, callback) {
    var _this = this;
    wx.request({
      url: G.APP_LINK + '/user/phone/decode',
      method: 'GET',
      data: {
        encryptedData: encryptedData,
        openid: openid,
        iv: iv
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data && res.statusCode == '200') {
          wx.setStorage({
            key: 'programUserInfo',
            data: res.data.data,
          })
          _this.globalData.programUserInfo = res.data.data;
          callback(res.data);
        } else {
          util.modalMsg('提示', '下单需要绑定您的电话', function () {
            console.log('用户点击取消')
            return;
          }, function () {
            console.log('用户点击取消')
            return;
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    })
  },
  userInfoReadyCallback(res, callback) {
    _this.judgeGetUserInfo(function (res) {
      console.log(res);
      callback(res);
    });
    console.log('userInfoReadyCallback: ', res);
    console.log('获取用户信息成功');
    _this.globalData.userInfo = res.userInfo
    _this.globalData.unauthorizedUserInfo = false;
  },
  // 拨打客服电话
  customerServiceTell: function () {
    var telPhone = _this.globalData.telPhone
    wx.makePhoneCall({
      phoneNumber: telPhone, //仅为示例，并非真实的电话号码
      success: function (res) {
        console.log(res, "success")
      },
      fail: function (res) {
        console.log(res, "fail")
      }
    })
  },
  // 获取 信息
  getMassage: function (data,id, url, callback, method) {
    var url = G.APP_LINK + link[url];
    id ? url = url + '/' + id:''; 
    wx.request({
      url: url,
      data: data ? data : {},
      method: method ? method:'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data) {
          callback(res.data);
        }
      },
      fail: function (res) {
        //TODO
        callback(false);
      }
    });
  },
  getList: function (page, limit, info, url, callback, method) {
    var url = G.APP_LINK + list[url];
    var data = info ? info : {};
    data.page = page;
    data.limit = limit;
    wx.request({
      url: url,
      data: data,
      method: method ? method : 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data) {
          callback(res.data);
        }
      },
      fail: function (res) {
        //TODO
        callback(false);
      }
    });
  },
  // 返回 跳转页面
  goBack: function (e, buttonClicked, _this){
    var delta = e.currentTarget.dataset.delta;
    if (!buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateBack({
        delta: delta
      })
    }
  },
  goNavTo: function (e, buttonClicked, _this){
    let url = e.currentTarget.dataset.url;
    let id = e.currentTarget.dataset.id;
    let salonId = e.currentTarget.dataset.salonId;
    id ? url = url + '?id=' +id : url;
    salonId ? url = url + '?salonId=' + salonId : url;
    if (!buttonClicked) {
      util.buttonClicked(_this);
      wx.navigateTo({
        url: url,
      })
    }
  }
})
